package com.zh.config.dialog

import android.net.Uri
import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zh.common.R
import com.zh.common.ktx.loadUrl
import com.zh.common.ktx.toast
import com.zh.common.utils.FileUtil
import com.zh.common.utils.OpenFileUtil
import com.zh.common.view.DownSeekView
import com.zh.common.view.RoundedImageView
import com.zh.config.db.DownEnum
import com.zh.config.db.DownloadDao
import com.zh.config.utils.DownloadFileUtils
import com.zh.config.utils.KnowledgeType
import java.io.File

class DownloadAdapter(private val showLine: Boolean = false) :
    BaseQuickAdapter<DownloadDao, BaseViewHolder>(R.layout.item_downloads) {

    private val listState = hashMapOf<String, Int>()

    override fun convert(holder: BaseViewHolder, item: DownloadDao) {
        holder.setText(R.id.tvName, item.name)
        holder.setText(R.id.tvSize, FileUtil.formatFileSize(item.total.toLong()))
        holder.setVisible(R.id.line, showLine)
        val ivLogo = holder.getView<RoundedImageView>(R.id.ivLogo)
        ivLogo.loadUrl(item.logo, getFileImage(item.logo))
        val tvDownload = holder.getView<DownSeekView>(R.id.tvDownload)

        listState[item.url] = item.state
        setTextState(item, tvDownload)
        tvDownload.setOnClickListener {
            when (listState[item.url]) {
                0 -> {
                    "开始下载".toast()
                    tvDownload.setText("准备")
                    /*if (!DownloadFileUtils.instance.hasTask(item.url)) {
                        DownloadFileUtils.instance.create(item)
                        bindListener(tvDownload, item)
                    }*/
                    DownloadFileUtils.instance.startTask(item.url, item.time)
                }

                1 -> {
                    DownloadFileUtils.instance.pauseTask(item.url, item.time)
                }

                2 -> {
                    DownloadFileUtils.instance.startTask(item.url, item.time)
                }

                3 -> {
                    /*tvDownload.context.showTipsDialog("下载失败，是否重新下载", sureTv = "下载") {
                        DownloadFileUtils.instance.startTask(item.url)
                        tvDownload.setText("准备")
                    }*/
                }

                4 -> {
//                    DownloadFileUtils.instance.installApp(item.filePath)
                    OpenFileUtil.openFile(context, item.filePath)
                }

                5 -> {
                    /*tvDownload.context.showTipsDialog("文件已删除，是否重新下载", sureTv = "下载") {
                        DownloadFileUtils.instance.startTask(item.url)
                        tvDownload.setText("准备")
                    }*/
                }
            }
        }

        bindListener(tvDownload, item)
    }

    private fun bindListener(tvDownload: DownSeekView, dao: DownloadDao) {
        /*DownloadFileUtils.instance.callList[dao.url]?.setListener(getListener(dao) {
            val dao2 = DownloadDao(dao.url, dao.name, dao.logo, dao.filePath, it.first, dao.total)
            setTextState(dao2, tvDownload, it.second)
            listState[dao.url] = it.first
        })*/
    }

    private fun setTextState(
        item: DownloadDao, tvDownload: DownSeekView, progress: Float = 0f
    ) {
        when (item.state) {
            0 -> {
                tvDownload.setText("下载")
            }

            1 -> {
                tvDownload.setProgress(progress)
            }

            2 -> {
                tvDownload.setText("暂停")
            }

            3 -> {
                tvDownload.setText("失败")
            }

            4 -> {
                tvDownload.setText("安装")
                tvDownload.setProgress(1f)
            }

            5 -> {
                tvDownload.setText("已删除")
            }
        }
    }

    /*private fun getListener(
        dao: DownloadDao, call: (Pair<Int, Float>) -> Unit
    ): FileDownloadListener {

        return object : FileDownloadListener() {
            override fun pending(
                task: BaseDownloadTask?,
                soFarBytes: Int,
                totalBytes: Int
            ) {
                if (task == null) return
                Log.d("BaseDownloadTask", "pending -> ${task.filename}")
                call.invoke(Pair(DownEnum.progress.state, 0f))
                val dao2 = DownloadDao(
                    dao.url, dao.name, dao.logo, dao.filePath, DownEnum.progress.state, dao.total
                )
                DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
            }

            override fun progress(
                task: BaseDownloadTask?,
                soFarBytes: Int,
                totalBytes: Int
            ) {
                if (task == null) return
                val progress = soFarBytes.toFloat() / totalBytes.toFloat()
                if (progress <= 1f) {
                    Log.d("BaseDownloadTask", "progress: $progress")
                    call.invoke(Pair(DownEnum.progress.state, progress))
                }
            }

            override fun completed(task: BaseDownloadTask?) {
                if (task == null) return
                Log.d("BaseDownloadTask", "completed -> ${task.filename}")
                if (dao.filePath.endsWith(".apk")) {
                    val file = File(dao.filePath)
                    if (file.exists() && file.length() > 1000) {
                        call.invoke(Pair(DownEnum.completed.state, 1f))
                        val dao2 = DownloadDao(
                            dao.url, dao.name, dao.logo, dao.filePath, DownEnum.completed.state,
                            dao.total
                        )
                        DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
                    } else {
                        call.invoke(Pair(DownEnum.error.state, 0f))
                        val dao2 = DownloadDao(
                            dao.url, dao.name, dao.logo, dao.filePath, DownEnum.error.state,
                            dao.total
                        )
                        DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
                    }
                } else {
                    call.invoke(Pair(DownEnum.completed.state, 1f))
                    val dao2 = DownloadDao(
                        dao.url, dao.name, dao.logo, dao.filePath, DownEnum.completed.state,
                        dao.total
                    )
                    DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
                }
            }

            override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                if (task == null) return
                Log.d("BaseDownloadTask", "paused -> ${task.filename}")
                call.invoke(Pair(DownEnum.paused.state, 0f))
                val dao2 = DownloadDao(
                    dao.url, dao.name, dao.logo, dao.filePath, DownEnum.paused.state, dao.total
                )
                DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
            }

            override fun error(task: BaseDownloadTask?, e: Throwable?) {
                if (task == null) return
                Log.d("BaseDownloadTask", "error -> ${task.filename} - ${e?.printStackTrace()}")
                call.invoke(Pair(DownEnum.error.state, 0f))
                val dao2 = DownloadDao(
                    dao.url, dao.name, dao.logo, dao.filePath, DownEnum.error.state, dao.total
                )
                DownloadFileUtils.instance.dbDownloadHelper.put(dao.url, dao2)
            }

            override fun warn(task: BaseDownloadTask?) {
            }
        }
    }*/

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        /*listState.keys.forEach {
            DownloadFileUtils.instance.callList[it]?.listener = null
        }*/
    }

    private fun getFileImage(path: String): Int {
        var url = path
        if (path.contains("?")) {
            url = path.split("?")[0]
        }
        val sp = Uri.parse(url).lastPathSegment?.split(".")
            ?: url.substring(url.lastIndexOf("/") + 1).split(".")
        var fileType = ""
        return R.mipmap.ic_launcher
        /*if (sp.size > 1) {
            fileType = sp[1].lowercase()
        } else {
            return R.mipmap.note
        }
        return if (fileType == KnowledgeType.k_pdf) {
            R.mipmap.pdf
        } else if (KnowledgeType.isVideo(fileType)) {
            R.mipmap.mp4
        } else if (fileType == KnowledgeType.k_txt) {
            R.mipmap.txt
        } else if (KnowledgeType.isImage(fileType)) {
            R.mipmap.pic
        } else if (fileType == KnowledgeType.k_pptx
            || fileType == KnowledgeType.k_ppt
        ) {
            R.mipmap.ppt
        } else if (fileType == KnowledgeType.k_wps) {
            R.mipmap.wps
        } else if (fileType == KnowledgeType.k_doc
            || fileType == KnowledgeType.k_docx
        ) {
            R.mipmap.doc
        } else if (fileType == KnowledgeType.k_xlsx
            || fileType == KnowledgeType.k_xls
        ) {
            R.mipmap.xlsx
        } else if (fileType == KnowledgeType.k_zip) {
            R.mipmap.zip
        } else if (fileType == KnowledgeType.k_xmind) {
            R.mipmap.xmind
        } else if (fileType == KnowledgeType.k_csv) {
            R.mipmap.csv
        } else {
            R.mipmap.note
        }*/
    }
}